
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE流式输出演示</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        #output {
            height: 300px;
            border: 1px solid #ccc;
            padding: 10px;
            margin-bottom: 20px;
            overflow-y: auto;
            white-space: pre-wrap;
        }
        #inputForm {
            display: flex;
            gap: 10px;
        }
        #userInput {
            flex-grow: 1;
            padding: 8px;
        }
        button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
    </style>
</head>
<body>
<h1>SSE流式输出演示</h1>
<div id="output">等待输入...</div>
<form id="inputForm">
    <input type="text" id="userInput" placeholder="请输入内容..." required>
    <button type="submit">发送</button>
</form>

<script>
    const outputDiv = document.getElementById('output');
    const inputForm = document.getElementById('inputForm');
    const userInput = document.getElementById('userInput');
    let eventSource = null;

    inputForm.addEventListener('submit', function(e) {
        e.preventDefault();
        const message = userInput.value.trim();
        if (!message) return;

        outputDiv.textContent = "等待响应...";
        userInput.value = '';

        // 关闭之前的SSE连接（如果存在）
        if (eventSource) {
            eventSource.close();
        }

        // 建立新的SSE连接
        eventSource = new EventSource(`http://localhost:8080/chatStream?message=${encodeURIComponent(message)}`);

        eventSource.onmessage = function(e) {
            outputDiv.textContent += e.data;
            outputDiv.scrollTop = outputDiv.scrollHeight;
        };

        eventSource.onerror = function() {
            eventSource.close();
            outputDiv.textContent += "\n\n连接已关闭";
        };
    });
</script>
</body>
</html>
